package com.ndp.fb.walle.controller;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.enums.ErrorType;
import com.ndp.fb.exception.AudienceSizeIsNotEnoughException;
import com.ndp.fb.exception.FormatException;
import com.ndp.fb.exception.NotSupportFileSuffixException;
import com.ndp.fb.exception.ParamException;
import com.ndp.fb.model.business.vo.cache.result.CustomAudienceCache;
import com.ndp.fb.rdb.model.Pager;
import com.ndp.fb.rdb.model.User;
import com.ndp.fb.rdb.model.customaudience.CustomAudienceItem;
import com.ndp.fb.util.ListUtil;
import com.ndp.fb.walle.business.CustomAudienceTemplateService;
import com.ndp.fb.walle.model.bo.customaudiencetemplate.result.CustomAudienceTemplateResult;
import com.ndp.fb.model.business.vo.BaseVoParam;
import com.ndp.fb.walle.model.vo.OutputResult;
import com.ndp.fb.walle.model.vo.PageResult;
import com.ndp.fb.walle.model.vo.customaudience.param.CustomAudienceDelParam;
import com.ndp.fb.walle.model.vo.customaudience.param.CustomAudienceParam;
import com.ndp.fb.walle.model.vo.customaudience.param.CustomAudienceRetryParam;
import com.ndp.fb.walle.model.vo.customaudience.param.CustomAudienceTemplateParam;
import com.ndp.fb.walle.model.vo.customaudience.result.CustomAudienceItemResult;
import com.ndp.fb.walle.util.ResponseUtils;

/**
 * Created by elvisxiong on 15/11/11.
 */
@RequestMapping("/customaudiencetemplate")
@Controller
public class CustomAudienceTemplateController {

    /**
     * LOG日志
     */
    private final org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private CustomAudienceTemplateService customAudienceTemplateService;

    /**
     * 创建受众
     * @param request
     * @return
     */
    @RequestMapping(value = "save")
    @ResponseBody
    public ResponseEntity<String> save(HttpServletRequest request) {
        logger.info("saveCustomAudience() begin.");
        ErrorType errorType;
        String userId = getUserId(request);
        User user = (User) request.getSession().getAttribute("user");
        try {
            String deliverType = request.getParameter("deliverType");
            String audienceType = request.getParameter("audienceType");
            String importedType = request.getParameter("importedType");
            String content = request.getParameter("content");
            String appIds = request.getParameter("appIds");
            appIds = URLDecoder.decode(appIds, "UTF-8");
            CustomAudienceTemplateParam customAudienceTemplateParam = new CustomAudienceTemplateParam();
            customAudienceTemplateParam.setCustomAudienceTemplateParam(deliverType,audienceType,importedType,content,appIds);
            customAudienceTemplateParam.setAudienceName("default");
            String contentPath = request.getRealPath("/");
            Map data = new HashMap<>();
            MultipartFile multipartFile = null;
            if (deliverType != null && deliverType.equals("UPLOAD_TEXT_FILE")) {
                multipartFile = getMultipartFile((MultipartHttpServletRequest) request, customAudienceTemplateParam, data);
            }
            int count = customAudienceTemplateService.saveCustomAudience(multipartFile, contentPath, customAudienceTemplateParam, userId,user.getOrgId());
            data.put("count", count);
            data.put("audienceTemplateId",customAudienceTemplateParam.getCustomAudienceTempateId());
            data.put("audienceName", customAudienceTemplateParam.getAudienceName());
            data.put("result", "success");
            OutputResult outputResult = ResponseUtils.bulidOutputResult(null, data);
            return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
        } catch (ParamException pex) {
            errorType = ErrorType.PARAM_EXCEPTION;
            logger.error("param exception!", pex);
        } catch (AudienceSizeIsNotEnoughException aex) {
            errorType = ErrorType.AUDIENCE_SIZE_NOT_ENOUGH_EXCEPTION;
            logger.error("audience size not enough", aex);
        }catch (NotSupportFileSuffixException supportFileSuffixException){
            errorType = ErrorType.NotSupportFileSuffixException;
            logger.error("not support file suffix exception",supportFileSuffixException);
        } catch (FormatException fex) {
            errorType = ErrorType.UPLOAD_FILE_FORMAT_EXCEPTION;
            logger.error("file format error!", fex);
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage());
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, null);
        logger.info("AdwordTagController searchTags() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    private MultipartFile getMultipartFile(MultipartHttpServletRequest request, CustomAudienceTemplateParam customAudienceTemplateParam, Map data) {
        MultipartFile  multipartFile = request.getFile("qqfile");
        if (multipartFile.isEmpty()) {
            data.put("count", 0);
            data.put("result", "fail");
        }else{
            String audienceName = multipartFile.getOriginalFilename();
            int index;
            if ((index = audienceName.indexOf(".")) != -1) {
                audienceName = audienceName.substring(0, index);
                customAudienceTemplateParam.setAudienceName(audienceName);
            }
        }
        return multipartFile;
    }

    private String getUserId(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        return user.getTicket() + "";
    }

    /**
     * 更新受众名称
     * @param param
     * @param request
     * @return
     */
    @RequestMapping(value = "updateName")
    @ResponseBody
    public ResponseEntity<String> updateName(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        logger.info("audienceCustom saveCustomAudience() begin.");
        OutputResult outputResult;
        try {
            User user = (User) request.getSession().getAttribute("user");
            JSONObject parseObject = JSONObject.parseObject(param);
            Long templateId = parseObject.getLong("templateId");
            String audienceName = parseObject.getString("audienceName");
            outputResult = customAudienceTemplateService.updateName(user, templateId, audienceName);
            return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
        } catch (Exception e) {
            logger.error("", e);
            outputResult = ResponseUtils.bulidOutputResult(ErrorType.INTERNAL_EXCEPTION, "fail");
        }
        logger.info("AdwordTagController updateName() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 更新受众
     * @param request
     * @return
     */
    @RequestMapping(value = "update")
    @ResponseBody
    public ResponseEntity<String> update(HttpServletRequest request) {
        logger.info("audienceCustom saveCustomAudience() begin.");
        OutputResult outputResult = null;
        ErrorType errorType = null;
        try {
            User user = (User) request.getSession().getAttribute("user");

            // 获得上传文件列表
            String templateId = request.getParameter("templateId"); //模板id
            String fileTypeString = request.getParameter("fileType"); //EMAIL PHONE FB_USER_ID MOBILE_ADVERTISER_IDS
            String editType = request.getParameter("editType"); // add remove replace
            String content = request.getParameter("content");
            String deliverType = request.getParameter("deliverType");
            MultipartFile multipartFile = null;
            if (deliverType != null && deliverType.equals("UPLOAD_TEXT_FILE")) {
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                multipartFile = multiRequest.getFile("qqfile");
            }

            if (multipartFile != null || StringUtils.isNotBlank(content)) {
                String contentPath = request.getRealPath("/");
                outputResult = customAudienceTemplateService.update(user, templateId, multipartFile, content, contentPath, fileTypeString, editType,deliverType);
            } else {
                outputResult = ResponseUtils.bulidOutputResult(ErrorType.CustomAudience_context_error_CustomAudience, "fail");
            }
        } catch (ParamException pex) {
            errorType = ErrorType.PARAM_EXCEPTION;
            logger.error("param exception!", pex);
        } catch (AudienceSizeIsNotEnoughException aex) {
            errorType = ErrorType.AUDIENCE_SIZE_NOT_ENOUGH_EXCEPTION;
            logger.error("audience size not enough", aex);
        }catch (NotSupportFileSuffixException supportFileSuffixException){
            errorType = ErrorType.NotSupportFileSuffixException;
            logger.error("not support file suffix exception",supportFileSuffixException);
        } catch (FormatException fex) {
            errorType = ErrorType.UPLOAD_FILE_FORMAT_EXCEPTION;
            logger.error("file format error!", fex);
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage());
        }
        if (outputResult == null) {
            outputResult = ResponseUtils.bulidOutputResult(errorType, "fail");
        }
        logger.info("AdwordTagController searchTags() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 自定义受众列表
     * @param param param
     * @param httpServletRequest httpServletRequest
     * @return ResponseEntity<String>
     */
    @RequestMapping(value = "list")
    @ResponseBody
    public ResponseEntity<String> findByPage(@RequestParam(value = "param", required = true) String param, HttpServletRequest httpServletRequest) {
        logger.info("CustomAudienceController findByPage() begin.");
        ErrorType errorType = null;
        Map<String, Object> data = null;
        try {

            User user = (User) httpServletRequest.getSession().getAttribute("user");
            CustomAudienceTemplateParam customAudienceTemplateParam = JSON.parseObject(param, CustomAudienceTemplateParam.class);
            int sizeNo = customAudienceTemplateParam.getPSize() == null ? CommonConstants.DEFAULT_PAGE_SIZE_100 : customAudienceTemplateParam.getPSize();
            int firstResult = customAudienceTemplateParam.getCPage() == null ? 0 : (customAudienceTemplateParam.getCPage() - 1) * sizeNo;

            // 查询列表
            Pager<CustomAudienceTemplateResult> customAudiencePager = customAudienceTemplateService.getCustomAudienceTemplateList(user.getOrgId(), user.getTicket(), customAudienceTemplateParam.getAudienceType(), customAudienceTemplateParam.getImportedType(), firstResult, sizeNo);

            // 计算分页结果
            long tSize = customAudiencePager.getTotalSize();
            float nrOfPages = (float) tSize / sizeNo;
            int tPage = (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages);
            PageResult pageResult = new PageResult(tPage, customAudienceTemplateParam.getCPage(), customAudienceTemplateParam.getPSize(), tSize);

            // 封装响应结果
            data = new HashMap<>();
            data.put("customaudiences", customAudiencePager.getResultList());
            data.put("paginator", pageResult);

        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error("CustomAudienceTemplateController findByPage error:", e);
        }

        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        logger.info("CustomAudienceController findByPage() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 受众上传详情
     * @param param
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "customAudienceItemList")
    @ResponseBody
    public ResponseEntity<String> customAudienceItemList(@RequestParam(value = "param", required = true) String param, HttpServletRequest httpServletRequest) {
        logger.info("CustomAudienceController customAudienceItemList() begin.");
        ErrorType errorType = null;
        Map<String, Object> data = null;
        try {
            BaseVoParam baseVoParam = JSON.parseObject(param, BaseVoParam.class);
            User user = (User) httpServletRequest.getSession().getAttribute("user");
            List<CustomAudienceItem> customAudienceItemList = customAudienceTemplateService.getCustomAudienceItemList(user.getTicket(),baseVoParam.getId());
            List<CustomAudienceItemResult> customAudienceItemResultList = new ArrayList<CustomAudienceItemResult>();
            for(CustomAudienceItem customAudienceItem :customAudienceItemList){
                customAudienceItemResultList.add(new CustomAudienceItemResult(customAudienceItem));
            }
            // 封装响应结果
            data = new HashMap<>();
            data.put("result", customAudienceItemResultList);

        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
        }

        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        logger.info("CustomAudienceController customAudienceItemList() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 自定义受众创建重试
     */
    @RequestMapping(value = "retryCustomAudience")
    @ResponseBody
    public ResponseEntity<String> retryCustomAudience(@RequestParam(value = "param", required = true) String param, HttpServletRequest httpServletRequest) {
        logger.info("CustomAudienceController retryCustomAudience() begin.");
        ErrorType errorType = null;
        User user = (User) httpServletRequest.getSession().getAttribute("user");
        try {
            CustomAudienceRetryParam par = JSON.parseObject(param, CustomAudienceRetryParam.class);
            customAudienceTemplateService.retryCustomAudience(par.getTmplId(), par.getFbAccountId(), par.getCustomAudienceDbId(), user.getTicket());
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, null);
        logger.info("CustomAudienceController retryCustomAudience() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 根据受众模板id删除 自定义受众
     *
     * @param param
     * @param request
     * @return
     */
    @RequestMapping(value = "del")
    @ResponseBody
    public ResponseEntity<String> del(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        logger.info("CustomAudienceController del() begin.");
        ErrorType errorType = null;
        Object result = null;
        User user = (User) request.getSession().getAttribute("user");
        try {
            CustomAudienceDelParam inParam = JSON.parseObject(param, CustomAudienceDelParam.class);
            if (inParam != null && ListUtil.isNotEmpty(inParam.getIds())){
                List<Long> hasLookALike = customAudienceTemplateService.findHasLookALike(inParam.getIds());
                if(hasLookALike.size() > 0 ){
                    result = hasLookALike;
                    errorType = ErrorType.Del_CustomAudience_Has_LookALike;
                } else {
                    customAudienceTemplateService.del(inParam, user.getTicket());
                }
            } else{
                errorType = ErrorType.PARAM_EXCEPTION;
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error("CustomAudienceController del()", e);
        }

        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, result);
        logger.info("CustomAudienceController del() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }
    /**
     * 根据受众模板id删除 自定义受众
     *
     * @param param
     * @param request
     * @return
     */
    @RequestMapping(value = "getCustomAudienceListByFbAccount")
    @ResponseBody
    public ResponseEntity<String> getCustomAudienceListByFbAccount(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        logger.info("CustomAudienceController getCustomAudienceListByFbAccount() begin.");
        ErrorType errorType = null;
        Object result = null;
        User user = (User) request.getSession().getAttribute("user");
        try {
        	CustomAudienceParam cParam = JSON.parseObject(param, CustomAudienceParam.class);
            if (cParam != null && cParam.getAccount_id()!=null){
            	//查询自定义受众和相似受众
                CustomAudienceCache cache = customAudienceTemplateService.buildEntrustAccountCustomAudienceCachesFBOK(cParam.getAccount_id());
                if(cache!=null&&ListUtil.isNotEmpty(cache.getCustomAudiences()))
                {
                	result = cache.getCustomAudiences();
                }
            } else{
                errorType = ErrorType.PARAM_EXCEPTION;
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error("CustomAudienceController del()", e);
        }

        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, result);
        logger.info("CustomAudienceController getCustomAudienceListByFbAccount() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }
    
}
